Difference between “struct” and “typedef struct” in C++?
Difference between “struct” and “typedef struct” in C++?
379
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023In C++, the
structkeyword is used to define a structure, which is a data type that can contain multiple different types of data. Thetypedefkeyword is used to create an alias for a data type.The main difference between
structandtypedef structis thatstructdefines a new data type, whiletypedef structsimply creates an alias for an existing data type. This means that you can use astructto declare variables, while you can only use atypedef structto refer to a variable that has already been declared using astruct.For example, the following code defines a
structcalledPoint:C++
The following code declares a variable of type
Point:C++
The following code declares a
typedefcalledPointthat refers to thestructof the same name:C++
The following code declares a variable of type
Point:C++
In both cases, the variable
pointwill be of typePoint. However, the first code defines a new data type calledPoint, while the second code simply creates an alias for the existing data typestruct Point.In general, you should use
structif you want to define a new data type. You should usetypedef structif you want to refer to an existing data type without having to write out the full name of the data type every time you want to use it.